import chalk from 'chalk';
import { DeepSeekClient } from '../modules/deepseek-client';

export interface TodoItem {
  id: number;
  title: string;
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
  description?: string;
  startTime?: Date;
  endTime?: Date;
}

export class AITodoManager {
  private todos: TodoItem[] = [];
  private currentId = 1;
  private deepseekClient: DeepSeekClient;

  constructor(deepseekClient: DeepSeekClient) {
    this.deepseekClient = deepseekClient;
  }

  async generateTodoList(taskDescription: string): Promise<TodoItem[]> {
    try {
      console.log(chalk.yellow('🤖 AI正在分析任务并生成执行计划...'));

      const prompt = `请分析以下运维任务，并生成详细的执行步骤清单：

任务描述：${taskDescription}

请以JSON格式返回，包含steps数组，每个步骤包含：
- title: 步骤标题（简短描述）
- description: 详细说明（可选）

要求：
1. 步骤要具体可执行
2. 按执行顺序排列
3. 包含验证步骤
4. 考虑可能的错误处理

示例格式：
{
  "steps": [
    {"title": "检查系统版本", "description": "确认操作系统类型和版本"},
    {"title": "更新软件包索引", "description": "执行apt update或yum update"},
    {"title": "安装软件包", "description": "安装所需的软件包"},
    {"title": "配置服务", "description": "修改配置文件"},
    {"title": "启动服务", "description": "启动并设置自启动"},
    {"title": "验证安装", "description": "测试功能是否正常"}
  ]
}`;

      const response = await this.deepseekClient.analyzeTask(prompt);

      let steps: any[] = [];
      try {
        const jsonMatch = response.content.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          const parsed = JSON.parse(jsonMatch[0]);
          steps = parsed.steps || [];
        }
      } catch (parseError) {
        // 如果解析失败，尝试从文本中提取步骤
        const lines = response.content.split('\n');
        steps = lines
          .filter(line => line.trim().match(/^\d+[\.\)]\s+/))
          .map((line, index) => ({
            title: line.replace(/^\d+[\.\)]\s+/, '').trim(),
            description: ''
          }));
      }

      // 生成Todo项目
      this.todos = steps.map((step, index) => ({
        id: index + 1,
        title: step.title || `步骤 ${index + 1}`,
        description: step.description,
        status: 'pending' as const
      }));

      this.currentId = steps.length + 1;
      this.displayTodoList();
      return [...this.todos];

    } catch (error) {
      console.log(chalk.red(`❌ 生成执行计划失败: ${error}`));
      return [];
    }
  }

  displayTodoList(): void {
    if (this.todos.length === 0) return;

    console.log(chalk.cyan('\n📋 执行计划:'));
    console.log(chalk.gray('─'.repeat(50)));

    this.todos.forEach((todo, index) => {
      const statusIcon = this.getStatusIcon(todo.status);
      const statusColor = this.getStatusColor(todo.status);

      console.log(`${statusIcon} ${index + 1}. ${statusColor(todo.title)}`);
      if (todo.description) {
        console.log(chalk.gray(`   ${todo.description}`));
      }
    });

    console.log(chalk.gray('─'.repeat(50)));
    this.displayProgress();
  }

  displayProgress(): void {
    const completed = this.todos.filter(t => t.status === 'completed').length;
    const failed = this.todos.filter(t => t.status === 'failed').length;
    const inProgress = this.todos.filter(t => t.status === 'in_progress').length;
    const total = this.todos.length;

    const progress = total > 0 ? Math.round((completed / total) * 100) : 0;

    console.log(chalk.cyan(`\n📊 执行进度: ${completed}/${total} (${progress}%)`));
    if (failed > 0) {
      console.log(chalk.red(`❌ 失败: ${failed}`));
    }
    if (inProgress > 0) {
      console.log(chalk.yellow(`🔄 进行中: ${inProgress}`));
    }
  }

  startStep(stepIndex: number): void {
    if (stepIndex >= 0 && stepIndex < this.todos.length) {
      this.todos[stepIndex].status = 'in_progress';
      this.todos[stepIndex].startTime = new Date();

      const todo = this.todos[stepIndex];
      console.log(chalk.yellow(`\n🔄 开始执行: ${todo.title}`));
      if (todo.description) {
        console.log(chalk.gray(`   ${todo.description}`));
      }
    }
  }

  completeStep(stepIndex: number, success: boolean = true): void {
    if (stepIndex >= 0 && stepIndex < this.todos.length) {
      this.todos[stepIndex].status = success ? 'completed' : 'failed';
      this.todos[stepIndex].endTime = new Date();

      const todo = this.todos[stepIndex];
      const icon = success ? '✅' : '❌';
      const color = success ? chalk.green : chalk.red;
      const statusText = success ? '完成' : '失败';

      console.log(color(`${icon} ${statusText}: ${todo.title}`));
      this.displayCurrentProgress();
    }
  }

  getCurrentStep(): TodoItem | null {
    const inProgress = this.todos.find(t => t.status === 'in_progress');
    if (inProgress) return inProgress;

    const nextPending = this.todos.find(t => t.status === 'pending');
    return nextPending || null;
  }

  getNextStepIndex(): number {
    return this.todos.findIndex(t => t.status === 'pending');
  }

  displayCurrentStatus(): void {
    const current = this.getCurrentStep();
    if (current) {
      const index = this.todos.findIndex(t => t.id === current.id);
      if (current.status === 'in_progress') {
        console.log(chalk.yellow(`🔄 当前步骤 [${index + 1}/${this.todos.length}]: ${current.title}`));
      } else {
        console.log(chalk.cyan(`⏳ 下一步骤 [${index + 1}/${this.todos.length}]: ${current.title}`));
      }
    } else {
      const completed = this.todos.filter(t => t.status === 'completed').length;
      const failed = this.todos.filter(t => t.status === 'failed').length;

      if (failed > 0) {
        console.log(chalk.red(`❌ 任务执行遇到问题，${failed}个步骤失败`));
      } else if (completed === this.todos.length) {
        console.log(chalk.green('🎉 所有步骤执行完成！'));
      }
    }
  }

  private displayCurrentProgress(): void {
    const completed = this.todos.filter(t => t.status === 'completed').length;
    const total = this.todos.length;
    const progress = Math.round((completed / total) * 100);

    console.log(chalk.gray(`   进度: ${completed}/${total} (${progress}%)`));
  }

  private getStatusIcon(status: TodoItem['status']): string {
    switch (status) {
      case 'pending': return '⏳';
      case 'in_progress': return '🔄';
      case 'completed': return '✅';
      case 'failed': return '❌';
      default: return '❓';
    }
  }

  private getStatusColor(status: TodoItem['status']): (text: string) => string {
    switch (status) {
      case 'pending': return chalk.gray;
      case 'in_progress': return chalk.yellow;
      case 'completed': return chalk.green;
      case 'failed': return chalk.red;
      default: return chalk.white;
    }
  }

  addCustomStep(title: string, description?: string): number {
    const todo: TodoItem = {
      id: this.currentId++,
      title,
      description,
      status: 'pending'
    };
    this.todos.push(todo);
    return this.todos.length - 1;
  }

  getTodos(): TodoItem[] {
    return [...this.todos];
  }

  isCompleted(): boolean {
    return this.todos.length > 0 && this.todos.every(t => t.status === 'completed');
  }

  hasFailed(): boolean {
    return this.todos.some(t => t.status === 'failed');
  }

  getCompletionSummary(): { completed: number; failed: number; total: number; duration?: string } {
    const completed = this.todos.filter(t => t.status === 'completed').length;
    const failed = this.todos.filter(t => t.status === 'failed').length;
    const total = this.todos.length;

    let duration: string | undefined;
    if (this.todos.length > 0) {
      const startTimes = this.todos.map(t => t.startTime).filter(Boolean) as Date[];
      const endTimes = this.todos.map(t => t.endTime).filter(Boolean) as Date[];

      if (startTimes.length > 0 && endTimes.length > 0) {
        const start = Math.min(...startTimes.map(t => t.getTime()));
        const end = Math.max(...endTimes.map(t => t.getTime()));
        const durationMs = end - start;
        duration = `${Math.round(durationMs / 1000)}秒`;
      }
    }

    return { completed, failed, total, duration };
  }
}